import Vue from 'vue';
import Vuex from 'vuex';

import db from '@/store/db.js';
import push from '@/store/push.js';
import {getAgoraRTMToken} from '@/api/configure.js';
import { getToken, setToken, removeToken, login } from '@/util/auth';
import { request } from '@/util/request.js';
import { deepClone } from '@/util/util.js';

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		isUniverifyLogin: false,
		loginProvider: "",
		openid: null,
		testvuex: false,
		colorIndex: 0,
		colorList: ['#FF0000', '#00FF00', '#0000FF'],
		noMatchLeftWindow: true,
		active: 'componentPage',
		leftWinActive: '/pages/component/view/view',
		activeOpen: '',
		menu: [],
		univerifyErrorMsg: '',
		//项目
		name: '',
		avatar: '',
		roles: [],
		permissions: [],
		token: getToken(),
		password: '',
		nearEvents: [],
		userInfo: {},
		agoraRTMToken: null
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setTestTrue(state) {
			state.testvuex = true
		},
		setTestFalse(state) {
			state.testvuex = false
		},
		setColorIndex(state, index) {
			state.colorIndex = index
		},
		setMatchLeftWindow(state, matchLeftWindow) {
			state.noMatchLeftWindow = !matchLeftWindow
		},
		setActive(state, tabPage) {
			state.active = tabPage
		},
		setLeftWinActive(state, leftWinActive) {
			state.leftWinActive = leftWinActive
		},
		setActiveOpen(state, activeOpen) {
			state.activeOpen = activeOpen
		},
		setMenu(state, menu) {
			state.menu = menu
		},
		setUniverifyLogin(state, payload) {
			typeof payload !== 'boolean' ? payload = !!payload : '';
			state.isUniverifyLogin = payload;
		},
		setUniverifyErrorMsg(state,payload = ''){
			state.univerifyErrorMsg = payload
		},

		//项目
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
		},
		setNearEevets: (state, events) =>{
			state.nearEvents = [];
			state.nearEvents = events.slice(0);
		},
		setUserInfo(state, obj) {
			state.userInfo = deepClone(obj);
		},
		getUserInfo(state, {userInfo}) {
			state.userInfo = userInfo;
		},
		getAgoraRTMToken(state, {token}) {
			state.agoraRTMToken = token;
		}
	},
	getters: {
		currentColor(state) {
			return state.colorList[state.colorIndex]
		},
		userloginform(state){
			return {name: state.name, password: state.password};
		},
		nearEvents(state) {
			return state.events;
		},
		userInfo(state) {
			return state.userInfo;
		}
	},
	actions: {
		// lazy loading openid
		getUserOpenId: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function() { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							reject(err)
						}
					})
				}
			})
		},
		getPhoneNumber: function({
			commit
		}, univerifyInfo) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/univerify-login',
					method: 'POST',
					data: univerifyInfo,
					success: (res) => {
						const data = res.data
						if (data.success) {
							resolve(data.phoneNumber)
						} else {
							reject(res)
						}

					},
					fail: (err) => {
						reject(res)
					}
				})
			})
		},
		//项目
		//获取用户登录信息

		getInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				request({
				  url: 'getInfo',
				  method: 'get',
				  data: state.token
				}).then(res => {
					const user = res.user;
					if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
						commit('SET_ROLES', res.roles)
						commit('SET_PERMISSIONS', res.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_NAME', user.userName)
					commit('SET_AVATAR', user.avatar)
					resolve(res)
				}).catch(error => {
					reject(error.msg)
				})
			})
		},
		async getUserInfo({commit, dispatch, state}) {
			return await new Promise(( resolve, reject) => {
				let userInfo = deepClone(uni.getStorageSync('userInfo'));

				commit({type: 'getUserInfo', userInfo: userInfo});

				resolve(state.userInfo)
			})
		},
		async getAgoraRTMToken({commit, dispatch, state}) {
			return await new Promise( async(resolve, reject) => {
				let {userId} = await dispatch('getUserInfo');

				let params = {
					userId
				}



				let {code, msg} = await getAgoraRTMToken(params);

				let token = msg;

				commit({type: 'getAgoraRTMToken', token});

				resolve(token);
			})
		},
		// 退出系统
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					removeToken()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 前端 登出
		FedLogOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				removeToken()
				resolve()
			})
		},
		// 获取附近的事件
		setNearEevets({commit, dispatch, state}, {events}) {
			return new Promise(resolve => {
				commit('setNearEevets', events);
				resolve()
			})
		},
		// 设置用户信息
		setUserInfo({commit, dispatch, state}, userInfo){
			return new Promise(resolve => {
				commit('setUserInfo', userInfo);
				resolve()
			})
		}
	},
	modules: {db, push}
})

export default store
